package com.xzgj.fmmall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xzgj.fmmall.dao.OrderItemMapper;
import com.xzgj.fmmall.dao.OrdersMapper;
import com.xzgj.fmmall.dao.ProductSkuMapper;
import com.xzgj.fmmall.dao.ShoppingCartMapper;
import com.xzgj.fmmall.entity.OrderItem;
import com.xzgj.fmmall.entity.Orders;
import com.xzgj.fmmall.entity.ProductSku;
import com.xzgj.fmmall.service.OrderService;
import com.xzgj.fmmall.vo.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.*;
@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private ShoppingCartMapper shoppingCartMapper;

    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private OrderItemMapper orderItemMapper;

    @Resource
    private ProductSkuMapper productSkuMapper;
    //当前订单套餐的总金额
    final static double actualAmount = 0.00;
    @Override
    /**
     *
     */
    public Map<String,String> addOrder(String cartIds,Orders order) {//根据情况需要什么参数就添加
        Map<String,String> map = new HashMap<>();
        //1.查询库存：根据cartIds查询当前订单中关联的购物车记录详情（包括库存）
        String[] arr = cartIds.split(",");
        List<Integer> cartIdsList = new ArrayList<>();
        for (int i = 0; i < arr.length; i++) {
            cartIdsList.add(Integer.parseInt(arr[i]));
        }
        List<ShoppingCartVO> list = shoppingCartMapper.selectShoppingCartByCartId(cartIdsList);
        if (list.size() <= 0){
            Map<String,String> resultMap = new  HashMap<>();
            resultMap.put("result",ResStatus.cartIsNotEmpty);
            return resultMap;
        }

        //保证cartNum<sku_stock
        //2.校验库存
        boolean f = true;
        String untitled = "";
        double total_amount = 0.00;
        double actualAmount = 0.00;
        for (ShoppingCartVO sc : list) {
            if (Integer.parseInt(sc.getCart_num()) > sc.getStock()) {//遍历商品后，有任一个商品的购物车数量>库存就表示库存不足
                f = false;
            }
            //获取所有商品名称以，分割拼接成字符串
            untitled = untitled + sc.getProduct_name() + ",";

            double temp_total_amount = Double.parseDouble(sc.getSell_price()) * Double.parseDouble(sc.getCart_num());
            total_amount += temp_total_amount;

            double temp_actualAmount = Double.parseDouble(sc.getSell_price()) * Double.parseDouble(sc.getCart_num());
            actualAmount += temp_actualAmount;
        }
        order.setPrice(total_amount);
        order.setActualAmount(actualAmount);

        if (f) {
            //表示库存充足---保存订单
            //需要
            // 1.userId
            // 2.untitled
            // 3.收货人信息:根据收货人地址的addrId查询收货地址信息
            // 4.总价格
            // 5.支付方式
            // 6.订单创建时间
            // 7.订单初始状态（待支付：1）
            order.setUntitled(untitled);
            order.setCreate_time(new Date());//订单完整了，要保存，保存之前要生成订单编号
            order.setStatus("1");
            //生成订单编号
            String orderId = UUID.randomUUID().toString().replace("-", "");
            order.setOrder_id(orderId);

            //保存订单
            int i = ordersMapper.insert(order);
            if (i > 0) {//保存订单成功
                //生成商品快照
                List<OrderItem> orderItems = new ArrayList<>();
                for (ShoppingCartVO sc : list) {
                    String itemId = System.currentTimeMillis() + "" + (new Random().nextInt(89999) + 10000);
                    total_amount = Double.parseDouble(sc.getSell_price()) * Double.parseDouble(sc.getCart_num());
                    OrderItem orderItem = new OrderItem(itemId, orderId, sc.getProduct_id(), sc.getProduct_name(), sc.getProductImg(), sc.getSku_id(), sc.getSku_name(), Double.parseDouble(sc.getSell_price()), sc.getCart_num(), total_amount + "", "1", "顺丰", "0");
                    orderItems.add(orderItem);

                }


                int j = orderItemMapper.insertList(orderItems);
                //扣减库存:根据套餐id修改套餐库存量
                for (ShoppingCartVO sc : list) {

                    String skuId = sc.getSku_id();
                    int newStock = sc.getStock() - Integer.parseInt(sc.getCart_num());

                    Example example = new Example(ProductSku.class);
                    Example.Criteria criteria = example.createCriteria();
                    criteria.andEqualTo("sku_id", skuId);

//                    ProductSku productSku = productSkuMapper.selectByPrimaryKey(skuId);
//                    productSku.setStock(String.valueOf(newStock));
                    //可以满足，但是操作了两次数据库
                    ProductSku productSku = new ProductSku();
                    productSku.setSku_id(Integer.parseInt(skuId));
                    productSku.setStock(String.valueOf(newStock));//updateByExampleSelective：为null的属性不操作;updateByPrimaryKeySelective通过对象的主键去操作不为null的对象

                    int k = productSkuMapper.updateByPrimaryKeySelective(productSku);
                }

                //删除购物车：当购物车中的记录购买成功后，购物车中对应记录做删除操作
                for (int buyCartIds: cartIdsList) {
                    shoppingCartMapper.deleteByPrimaryKey(buyCartIds);
                }
//存储一个map ：包含 orderId,untitled,回调返回给控制器，用来支付订单时提交参数
                map.put("orderId",orderId);
                map.put("productNames",untitled);

                return map;// new ResultVO(ResStatus.OK, ResStatus.orderSuccess, orderId);

            }
        } else {
            //表示库存不足
            return null;//new ResultVO(ResStatus.NO, ResStatus.productSkuStockIsNotEnough, null);
        }
        return null;//new ResultVO(ResStatus.OK,ResStatus.SUCCESS,null);
    }

    @Override
    public int updateOrderStatus(String orderId, String status) {
        Orders orders = new Orders();
        orders.setOrder_id(orderId);
        orders.setStatus(status);
        int i  = ordersMapper.updateByPrimaryKeySelective(orders);
        return i;
    }

    @Override
    public ResultVO getOrderStatusByOrderId(String orderId) {
        Orders orders = ordersMapper.selectByPrimaryKey(orderId);
        return new ResultVO(ResStatus.OK,ResStatus.SUCCESS,orders.getStatus());
    }

    @Override
    /**
     * 一个商品存在两个订单中，都要还原库存，就会出现并发问题：
     * 解决方案：1.设置隔离级别(事务锁) Isolation.SERIALIZABLE,即串行化，依次操作执行
     *          2.synchronized(JVM锁)
     */
    @Transactional(isolation = Isolation.SERIALIZABLE)
    public void closeOrder(String orderId) {

        synchronized (this){
            // 2.2.1 向微信支付平台发送请求，关闭当前订单的支付链接---这样用户就不能支付，因为订单已关闭
            // 2.2.2 修改当前订单：status=6 已关闭 close_type=1 超时未支付
            Orders cancelOrder = new Orders();
            cancelOrder.setOrder_id(orderId);
            cancelOrder.setStatus("6");//已关闭订单
            cancelOrder.setClose_type(1);//关闭类型：超时未支付
            ordersMapper.updateByPrimaryKeySelective(cancelOrder);
            // 2.2.3 还原库存：先根据当前订单编号查询商品快照（sku_id,buy_count）---修改product_sku表，添加回库存
            Example restoreExample = new Example(OrderItem.class);
            Example.Criteria restoreCriteria = restoreExample.createCriteria();
            restoreCriteria.andEqualTo("order_id",orderId);
            List<OrderItem> orderItems = orderItemMapper.selectByExample(restoreExample);
            //还原库存
            for (int j = 0;j < orderItems.size();j++){
                OrderItem orderItem = orderItems.get(j);
                //修改库存:先通过商品快照拿到原商品的套餐productSku，再获取商品原库存 + 当前商品的buy_counts
                ProductSku productSku = productSkuMapper.selectByPrimaryKey(orderItem.getSku_id());
                productSku.setStock(productSku.getStock() + orderItem.getBuy_counts());
                productSkuMapper.updateByPrimaryKey(productSku);//更新库存，即还原库存
            }
        }

    }

    @Override
    public PageInfo<Orders> getOrdersList(int pageNo, int pageSize) {
        PageHelper.startPage(pageNo,pageSize);
        List<Orders> orders = ordersMapper.selectAll();
        PageInfo<Orders> pageInfo = new PageInfo<>(orders);
        return pageInfo;
    }

    @Override
    public PageInfo<OrdersVO> listOrders(String userId, String status, int pageNo, int pageSize) {
        //1.分页查询
        int start = (pageNo - 1) * pageSize;
        List<OrdersVO> ordersVOS = ordersMapper.selectOrders(userId,status,pageNo,pageSize);
        if (ordersVOS.size() == 0){
            return new PageInfo<>(new ArrayList<>());
        }
        //2.查询总记录数
        Example example = new Example(Orders.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andLike("user_id",userId);
        if (status != null && !"".equals(status)){
            criteria.andLike("status",status);
        }
        int count = ordersMapper.selectCountByExample(example);
        //3.计算总页数
        int pageCount = count%pageSize==0?count/pageSize:count/pageSize+1;
        //4.封装数据

        PageHelper.startPage(pageNo,pageSize);
        PageInfo<OrdersVO> pageInfo = new PageInfo<>(ordersVOS);

        return pageInfo;
    }

}
